/**
 * 
 */
package com.ginger.rabbitmq.convert;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

import com.ginger.rabbitmq.properties.RabbitMQProperties;

/**
 * @Description: 图像消息类型转换
 * @author 姜锋
 * @date 2019年4月1日 下午1:55:09 
 * @version V1.0   
 *
 */
public class ImageMessageConverter implements MessageConverter{
	/** 日志对象 **/
	private final static Logger logger = LoggerFactory.getLogger(ImageMessageConverter.class);
	
	@Override
	public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
		throw new MessageConversionException(" convert error ! ");
	}

	@Override
	public Object fromMessage(Message message) throws MessageConversionException {
		logger.warn("-----------Image MessageConverter----------");
		
		Object _extName = message.getMessageProperties().getHeaders().get("extName");
		String extName = _extName == null ? "png" : _extName.toString();
		
		byte[] body = message.getBody();
		String fileName = UUID.randomUUID().toString();
		
		File f = new File(Paths.get(RabbitMQProperties.STORAGE_DIR,fileName + "." + extName).toString());
		try {
			Files.copy(new ByteArrayInputStream(body), f.toPath());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return f;
	}
}
